package com.ktgj.customer.common;

import com.alibaba.fastjson.JSONObject;
import com.ktgj.common.core.constant.InsuranceTypeEnum;
import com.ktgj.customer.domain.Insurance.heydayModel.HeydayUrlInfo;
import com.ktgj.customer.domain.Insurance.Encryption;
import com.ktgj.customer.domain.Insurance.heydayModel.Heyday;
import com.ktgj.customer.util.EncryptUtil;
import com.ktgj.customer.util.HttpPostUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class HeydayUtils
{
    @Value("${heyday-insurance.heydayFilePath}")
    private String heydayCerPath;
//    //测试环境
//    //火车意外险
//    private static String train = "https://test-h5.dsibc.com/h5/product?token=bae67ca2322547b0bd863db674717514";
//    //航空意外险
//    private static String aviation = "https://test-h5.dsibc.com/h5/product?token=8123fc38413e4325a08d5219a10c06f6";
    private static String channelId ="231";
    private static String method ="H5_INSURE";
    private static String salesmanId ="2310048";
    private static String version ="1.0.0";

    //鼎盛保险链接获取
    public HeydayUrlInfo heydayInsurance(String type) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String time = format.format(date);

        Heyday heyday = new Heyday();
        heyday.setChannelPolicyNo(time);
        heyday.setRequestDate(time);
        heyday.setNotifyUrl("http://106.38.39.137:8080/customer/callback/heydayCallback");
        if (type.equals(InsuranceTypeEnum.train.getValue())){
            heyday.setProductId("1061901");
        }
        else if (type.equals(InsuranceTypeEnum.aviation.getValue())){
            heyday.setProductId("1061902");
        }
        heyday.setCompanyId("103");

        String content = JSONObject.toJSONString(heyday);

        String privateKeyPwd="123456";
//        String desString = encrypt(content,privateKeyPwd,downloadPrivateKey(heydayCerPath));
        String desString = encrypt(content,privateKeyPwd,downloadPrivateKey("C:\\Users\\a1874\\Desktop\\2310048_pri.pfx"));
//        System.out.println(desString);

        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("channelId",channelId);
        paramsMap.put("method",method);
        paramsMap.put("salesmanId",salesmanId);
        paramsMap.put("version",version);
        paramsMap.put("message",desString);
        String desContent = HttpPostUtil.post("https://test-h5.dsibc.com/insurance-gateway/gateway",paramsMap);

        Encryption result = JSONObject.parseObject(desContent, Encryption.class);

        if (result.getResponseCode().equals("000000")){
            desContent = result.getMessage();
        }
        else {
            throw new Exception(result.getResponseMsg());
        }

        String platormPublicKey="-----BEGIN CERTIFICATE-----\n" +
                "MIICAjCCAWugAwIBAgIGAYGP4XbRMA0GCSqGSIb3DQEBDQUAMCExEjAQBgNVBAoMCUNGQ0EgT0NB\n" +
                "MTELMAkGA1UEBhMCQ04wHhcNMjIwNjIzMDkyNTI2WhcNMjMwNjIzMDkyNTI2WjBoMREwDwYDVQQD\n" +
                "DAhrY2JlYmFuazEXMBUGA1UECwwOa2NiZWJhbmstcnV5YW4xGTAXBgNVBAsMEE9yZ2FuaXphdGlv\n" +
                "bmFsLTExEjAQBgNVBAoMCUNGQ0EgT0NBMTELMAkGA1UEBhMCQ04wgZ8wDQYJKoZIhvcNAQEBBQAD\n" +
                "gY0AMIGJAoGBALS+r6NTKz+XhzeM0J2PI/KJSIM2KA49R4Fj9fUQ5pkCAm9Kyx6zdhquMlNBvCdD\n" +
                "MosQpSehz2GCoTiMALmHDUMHY7D61hiMKgjaFXep7A5gE0Xh4BnRq4CAJfkL09504RSD+dNksnCr\n" +
                "1QqUlAmLifAIpU0Q1T8swNQ832vnz9ZRAgMBAAEwDQYJKoZIhvcNAQENBQADgYEADZVYDF6ATNu8\n" +
                "wlvpu3XXGV/JC+qqnY8PaGiCg/n/BHnO71ER+JoJuI6UYq35Du2UUEpzR0BfPB4FnxolMtvjrFNx\n" +
                "vmVW2EeaYFdBhs7ZeAh3nCkh3Hv5dQ2W65vwyhtQmTGzZcCyJzhmILctO3q64D6lHlD15clUUHbH\n" +
                "mf3HJwo=\n" +
                "-----END CERTIFICATE-----";
        String decrypt = decrypt(desContent, platormPublicKey);
        HeydayUrlInfo decryptInfo = JSONObject.parseObject(decrypt, HeydayUrlInfo.class);
        return decryptInfo;
    }

    public String encrypt(String signContent,String keyPwd,byte[] key) throws Exception {
        return EncryptUtil.encrypt(signContent,keyPwd,key);
    }

    public String decrypt(String content,String publicKey) throws IOException {
        return EncryptUtil.decryption(content,publicKey);
    }

    public byte[] downloadPrivateKey(String path) throws IOException {
        BufferedInputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] bytes = null;
        try {
            File file = new File(path);
            in = new BufferedInputStream(new FileInputStream(file));
            out = new ByteArrayOutputStream(1024);
            byte[] temp = new byte[1024];
            int size = 0;
            while((size = in.read(temp)) != -1){
                out.write(temp,0,size);
            }
            bytes = out.toByteArray();
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    System.out.println("输入流关闭失败：{}"+e);
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    System.out.println("输入流关闭失败：{}"+e);
                }
            }
        }
        return bytes;
    }
}
